﻿
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Linq;
using System.Collections.Generic;
using System;
using AutoMapper;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore.Internal;


using System.Linq.Expressions;
using LinqKit;
using Ccteg.Common;
using CCcteg.Common;
using Ccteg.DB;
using Cari.IBP.Platform.Sidecar;
using Microsoft.EntityFrameworkCore;

namespace Cctegaq.Api.Controllers
{
    /// <summary>
    /// 事故隐患排查
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HTCController : IbpControllerBase
    {
        private readonly AppAuthenticationSettings _appSettings;
        private readonly MySqlDbContext _dbContext;
        private readonly IMapper _mapper;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="appSettings"></param>
        /// <param name="dbContext"></param>
        /// <param name="mapper"></param>
        public HTCController(IOptions<AppAuthenticationSettings> appSettings, MySqlDbContext dbContext, IMapper mapper)
        {
            _appSettings = appSettings.Value;
            _dbContext = dbContext;
            _mapper = mapper;
        }
        ///// <summary>
        ///// 事故隐患排查---处置状态
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //public ResponseResultModel<IEnumerable<Htc_NowState_ViewModel>> HtcNowStateSearch()
        //{
        //    using (_dbContext)
        //    {
        //        Expression<Func<Htc_Trouble, bool>> where = p => true;
        //        where = where.And(x => x.Deleted == false).And(x => x.Level != null);
        //        var query = _dbContext.Htc_Trouble.AsQueryable().Where(where.Expand()).GroupBy(x => x.NowState).Select(group => new Htc_NowState_ViewModel { NowState=group.Key });
        //        var response = ResponseModelFactory<IEnumerable<Htc_NowState_ViewModel>>.CreateResultInstance;
        //        response.SetData(query, query.Count());
        //        return response;
        //    }
        //}
        /// <summary>
        /// 事故隐患排查查询
        /// </summary>
        /// <param name="companyno">受检单位--二级单位编码</param>
        /// <param name="level">隐患等级</param>
        ///  <param name="category">隐患分类</param>
        /// <param name="describe">隐患描述</param>
        /// <param name="nowstate">状态</param>
        /// <param name="checktimestart">检查时间--开始时间</param>
        /// <param name="checktimeend">检查时间--结束时间</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">显示条数</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseResultModel<IEnumerable<Htc_Trouble_ViewModel>> HtcTroubleSearch(string companyno, string level, string category, string describe, string nowstate, DateTime? checktimestart, DateTime? checktimeend, int pageindex = 1, int pagesize = 10)
        {
            using (_dbContext)
            {


                var response = ResponseModelFactory<IEnumerable<Htc_Trouble_ViewModel>>.CreateResultInstance;
                Expression<Func<Htc_Trouble, bool>> where = p => true;


                where = where.CheckNullAnd(x => x.CompanyNo == companyno, companyno);
                where = where.CheckNullAnd(x => x.Level == level, level);
                where = where.CheckNullAnd(x => x.Category == category, category);
                where = where.CheckNullAnd(x => x.Describe.Contains(describe), describe);
                where = where.CheckNullAnd(x => x.NowState == nowstate, nowstate);
                where = where.CheckNullAnd(x => x.CheckTime > checktimestart, checktimestart);
                where = where.CheckNullAnd(x => x.CheckTime <= checktimeend, checktimeend);

                var query = _dbContext.Htc_Trouble.AsQueryable();

                query = query.Where(where.Expand()).OrderByDescending(x => x.Id);

                var list = query.Paged(pageindex, pagesize).ToList();
                var totalCount = query.Count();
                var data = list.Select(_mapper.Map<Htc_Trouble, Htc_Trouble_ViewModel>);
                response.SetData(data, totalCount);
                return response;
            }
        }
        /// <summary>
        /// 事故隐患排查 删除
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel HTCDelete([Required] int id)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var res = _dbContext.Htc_Trouble.Where(x => x.Id == id)
                        .SetField(x => x.Deleted).WithValue(true)
                        .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                        .SetField(x => x.ModifiedBy).WithValue("系统")
                        .Update();
                    if (res > 0)
                        response.SetSuccess("删除成功");
                    else
                        response.SetFailed("删除失败");

                }

            }
            catch (Exception ex)
            {
                response.SetFailed("删除失败");
                response.Data = ex.Message;
            }
            return response;
        }

        /// <summary>
        /// 事故隐患排查 添加 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel HTCAddOrUpdate([FromBody] Htc_Trouble_ViewModel model)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    var entity = _mapper.Map<Htc_Trouble_ViewModel, Htc_Trouble>(model);
                    var entryEntity = _dbContext.Htc_Trouble.Attach(entity);
                    if (entity.Id > 0)
                    {
                        var editentity = _dbContext.Htc_Trouble.AsNoTracking().Where(x => x.Id == entity.Id && x.Deleted == false).AsNoTracking().FirstOrDefault();
                        if (editentity == null)
                        {
                            response.SetFailed("无法修改，数据不存在请刷新页面");
                            return response;
                        }
                        entryEntity.State = EntityState.Modified;
                        entryEntity.Property(p => p.CreatedOn).IsModified = false;
                        entryEntity.Property(p => p.CreatedBy).IsModified = false;
                        entryEntity.Property(p => p.CompanyName).IsModified = false;
                        entryEntity.Property(p => p.CompanyNo).IsModified = false;
                        entryEntity.Property(p => p.Deleted).IsModified = false;
                        entity.ModifiedBy = "系统";
                        entity.ModifiedOn = System.DateTime.Now;
                        entity.DataSource = "集团检查";
                    }
                    else
                    {
                        entryEntity.Property(p => p.ModifiedBy).IsModified = false;
                        entryEntity.Property(p => p.ModifiedOn).IsModified = false;
                        entity.Deleted = false;
                        entity.CreatedBy = "系统";
                        entity.CreatedOn = System.DateTime.Now;
                        entity.CompanyName = " 中国煤科";
                        entity.CompanyFullName = "中国煤科";
                        entity.CompanyNo = "001";
                        entity.DataSource = "集团检查";

                    }
                    _dbContext.SaveChanges();
                    response.SetSuccess("操作成功");

                }
            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }
    }
}